package com.risenetsoft.elasticsearch.api;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Zhanggd on 2017/8/9.
 */
public class AggregationDemo {
    public static final String CLUSTER_NAME = "elasticsearch"; //实例名称
    private static final int PORT = 9300;  //端口
    private static final String IP = "192.168.190.104";
    private static Settings settings = Settings.builder()
            .put("cluster.name",CLUSTER_NAME)
            .put("client.transport.sniff",true)
            .put("client.transport.ping_timeout","120s")
            .build();

    private static TransportClient client;
    static {
        try {
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(IP), PORT));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        structAggregate();


    }


    private static void structAggregate() {
        SearchResponse searchResponse = client.prepareSearch()
                .addAggregation(AggregationBuilders.terms("by_country").field("country")
                        .subAggregation(AggregationBuilders.dateHistogram("by_year")
                                .field("dateOfBirth")
                                .dateHistogramInterval(DateHistogramInterval.YEAR)
                                .subAggregation(AggregationBuilders.avg("avg_children").field("children")))
                ).execute().actionGet();
    }


}
